package server_agent

import (
	"context"
	"lark/conf"
	"lark/util"
	"time"

	etcdclient "github.com/coreos/etcd/clientv3"
	"github.com/pkg/errors"
)

/*
采用短连接向 etcd 集群上报
忽略get key 和 keep once 之间，可能 lease 已经过期的情况。等下一次客户端触发
*/

func KeepAlive(cli *etcdclient.Client, key string, ch chan error) {
	util.PrintPanicStack()

	ctx, cancel := context.WithTimeout(context.Background(), time.Second*3)
	defer cancel()

	resp, err := cli.Get(ctx, key)
	if err != nil {
		ch <- errors.WithStack(err)
		return
	}

	if len(resp.Kvs) == 0 {
		leaseResp, err := cli.Grant(ctx, 15)
		if err != nil {
			ch <- errors.WithStack(err)
			return
		}

		_, err = cli.Put(ctx, key, conf.Version, etcdclient.WithLease(leaseResp.ID))
		if err != nil {
			ch <- errors.WithStack(err)
			return
		}

	} else {
		_, err = cli.KeepAliveOnce(ctx, etcdclient.LeaseID(resp.Kvs[0].Lease))
		if err != nil {
			ch <- errors.WithStack(err)
			return
		}
	}

	ch <- nil
}

func Revoke(cli *etcdclient.Client, key string, ch chan error) {
	util.PrintPanicStack()

	ctx, cancel := context.WithTimeout(context.Background(), time.Second*3)
	defer cancel()

	resp, err := cli.Get(ctx, key)
	if err != nil {
		ch <- errors.WithStack(err)
		return
	}

	if len(resp.Kvs) == 0 {
		ch <- nil
		return
	} else {
		_, err = cli.Revoke(ctx, etcdclient.LeaseID(resp.Kvs[0].Lease))
		if err != nil {
			ch <- errors.WithStack(err)
			return
		}
	}

	ch <- nil
}
